﻿using System;
using System.Data.SqlServerCe;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace Home.Mobilesales.Common
{
    public class OtherException:Exception
    {
        public OtherException(string message) : base(message){}
    }

    public static class ExceptionWork
    {
       public static void ExeptionProcess(Exception e)
        {
            string message = string.Empty;
            StringBuilder record = new StringBuilder();
            try
            {
                throw e;
            }
            catch (SqlCeException ex)
            {
                message = "Помилка при роботі з БД";
                record.Append(DateTime.Now.ToString() + "\t");
                record.Append(ex.NativeError + "\t" + ex.Message + "\t" + ex.Source + "\t" + ex.StackTrace);
            }
            catch (OtherException ex)
            {
                message = ex.Message;
            }
            catch (Exception ex)
            {
                message = "Помилка";
                record.Append(DateTime.Now.ToString() + " ");
                record.Append(ex.Message + "\t" + ex.StackTrace);
            }
            finally
            {
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand,
                                MessageBoxDefaultButton.Button1);
                try
                {
                    string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
                    using (StreamWriter sw = new StreamWriter(path + "\\Error.log", true))
                    {
                        sw.WriteLine(record.ToString());
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Помилка при збереженні логу", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand,
                                    MessageBoxDefaultButton.Button1);
                }

            }
        }
    }
}
